import qrcode
import os
import random
import string
from PIL import Image, ImageDraw

# 生成随机订单号
def generate_random_string(length=12):
    characters = string.ascii_uppercase + string.digits
    return ''.join(random.choice(characters) for _ in range(length))

# 定义二维码保存路径
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
qrcode_dir = os.path.join(base_dir, 'static', 'images', 'qrcodes')

# 确保目录存在
os.makedirs(qrcode_dir, exist_ok=True)

# 生成不同面额的二维码
amounts = ['10', '20', '50', '100', '200', '500']

# 为微信和支付宝分别生成二维码
for payment_method in ['wechat', 'alipay']:
    for amount in amounts:
        # 生成随机支付数据
        order_no = generate_random_string()
        payment_data = f"{payment_method.upper()}_PAY_{amount}_YUAN_ORDER_{order_no}"
        
        # 创建二维码
        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data(payment_data)
        qr.make(fit=True)
        
        # 创建图片
        img = qr.make_image(fill_color="black", back_color="white")
        
        # 添加支付方式的标志
        if payment_method == 'wechat':
            # 微信绿色
            color = (7, 193, 96)
        else:
            # 支付宝蓝色
            color = (22, 119, 255)
        
        # 在二维码中间绘制一个彩色方块
        draw = ImageDraw.Draw(img)
        img_width, img_height = img.size
        center_size = img_width // 10
        center_pos = (img_width // 2 - center_size // 2, img_height // 2 - center_size // 2)
        draw.rectangle(
            [center_pos, (center_pos[0] + center_size, center_pos[1] + center_size)],
            fill=color
        )
        
        # 保存图片
        filename = f"{payment_method}_{amount}.png"
        filepath = os.path.join(qrcode_dir, filename)
        img.save(filepath)
        
        print(f"Generated: {filepath}")

print("All QR codes generated successfully!") 